package com.bnlr.lrparking.appui.web;

import android.content.Context;
import android.content.pm.ActivityInfo;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.GeolocationPermissions;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.blankj.utilcode.util.ToastUtils;
import com.bnlr.lrparking.app.Application;
import com.bnlr.lrparking.R;
import com.bnlr.lrparking.base.BaseActivity;
import com.bnlr.lrparking.app.AppConfig;
import com.bnlr.lrparking.constant.LrConstant;
import com.bnlr.lrparking.constant.Urls;
import com.bnlr.lrparking.util.CommonUtil;
import com.bnlr.nohttp.CallServer;
import com.bnlr.nohttp.CustomHttpListener;
import com.yolanda.nohttp.NoHttp;

import org.json.JSONArray;
import org.json.JSONObject;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * Created by Administrator on 2017/3/2.
 * 根据intent 加载不同内容的web view
 *
 * @author hp
 */
public class WebActivity extends BaseActivity {

    @BindView(R.id.wv)
    WebView web;
    @BindView(R.id.activity_web)
    LinearLayout activityWeb;
    @BindView(R.id.tv_nav_title)
    TextView tvNavTitle;
    int tag = 0;
    private String link = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_web);
        ButterKnife.bind(this);

        tag = getIntent().getIntExtra("tag", 0);
        switch (tag) {
            case 1:
                tvNavTitle.setText("关于我们");
                getData();
                break;
            case 2:
                tvNavTitle.setText("帮助中心");
                web.loadUrl(Urls.URL_SUPPORT_CENTER);
                break;
            case 3:
                tvNavTitle.setText("服务条款");
                web.loadUrl(Urls.URL_TERMS_SERVICE);
                break;
            case 4:
                tvNavTitle.setText("版本说明");
                web.loadUrl(Urls.URL_RELEASE_NOTES);
                break;
            case 5:
                tvNavTitle.setText("消息详情");
                getData();
                break;
            case 6:
                tvNavTitle.setText("利人停车使用协议");
                getData();
                break;
            case 7:
                tvNavTitle.setText("利人停车-发布信息服务协议");
                getData();
                break;
            case 8:
                tvNavTitle.setText("车位保留协议书");
                getData();
                break;
            default:
                break;

        }

    }

    public void init_title() {
        web.getSettings().setJavaScriptEnabled(true);
        web.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
        web.getSettings().setPluginState(WebSettings.PluginState.ON);
        web.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        web.setWebViewClient(new WebViewClient());
        web.setBackgroundColor(getResources().getColor(R.color.bg_color));
        //设置js可以直接打开窗口，如window.open()，默认为false
        web.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
        //设置此属性，可任意比例缩放。大视图模式
        web.getSettings().setUseWideViewPort(true);
        //和setUseWideViewPort(true)一起解决网页自适应问题
        web.getSettings().setLoadWithOverviewMode(true);
        //是否使用缓存
        web.getSettings().setAppCacheEnabled(true);
        //启用数据库
        web.getSettings().setDatabaseEnabled(true);
        //设置定位的数据库路径
        String dir = this.getApplicationContext().getDir("database", Context.MODE_PRIVATE).getPath();
        web.getSettings().setGeolocationDatabasePath(dir);
        //启用地理定位
        web.requestFocus();
        web.getSettings().setGeolocationEnabled(true);
        //DOM Storage
        web.getSettings().setDomStorageEnabled(true);
        web.setWebChromeClient(myChromeClient);
    }

    String title, content, date, messageId = "";

    @Override
    public void getData() {
        super.getData();
        try {
            mRequest = NoHttp.createStringRequest(Urls.IP, LrConstant.POST);

            mRequest.add("phonePara", Application.DEVICE_ID);
            switch (tag) {
                case 1:
                    mRequest.add("uid", AppConfig.getInstance().getString("uid", ""));
                    mRequest.add("action", "GetWenZhang");
                    mRequest.add("ca", "52");
                    break;
               /* case 2:
                    mRequest.add("uid", AppConfig.getInstance().getString("uid", ""));
                    mRequest.add("action", "GetWenZhang");
                    mRequest.add("ca", "53");
                    break;*/
               /* case 3:
                    mRequest.add("uid", AppConfig.getInstance().getString("uid", ""));
                    mRequest.add("action", "GetWenZhang");
                    mRequest.add("ca", "54");
                    break;*/
               /* case 4:
                    mRequest.add("uid", AppConfig.getInstance().getString("uid", ""));
                    mRequest.add("action", "GetWenZhang");
                    mRequest.add("ca", "56");
                    break;*/
                case 5:
                    mRequest.add("action", "GetMessageById");
                    mRequest.add("uid", AppConfig.getInstance().getString("uid", ""));
                    mRequest.add("id", getIntent().getStringExtra("id"));
                    break;
                case 6:
                    mRequest.add("uid", AppConfig.getInstance().getString("uid", ""));
                    mRequest.add("action", "GetWenZhang");
                    mRequest.add("ca", "57");
                    break;
                case 7:
                    mRequest.add("uid", AppConfig.getInstance().getString("uid", ""));
                    mRequest.add("action", "GetWenZhang");
                    mRequest.add("ca", "58");
                    break;
                case 8:
                    mRequest.add("uid", AppConfig.getInstance().getString("uid", ""));
                    mRequest.add("action", "GetWenZhang");
                    mRequest.add("ca", "59");
                    break;
                default:
                    break;
            }

            // 添加到请求队列
            CallServer.getRequestInstance().add(baseContext, mRequest,
                    new CustomHttpListener<JSONObject>(baseContext, true, JSONObject.class) {
                        @Override
                        public void doWork(JSONObject data, String code) {

                        }

                        @Override
                        public void onFinally(JSONObject obj, String code, boolean isSucceed) {
                            try {
                                super.onFinally(obj, code, isSucceed);
                                //{"msgcode":"1","msg":"成功","data":{"id":"104","title":"测试啊都是啥地方都是反倒是都是","linkUrl":"","imgUrl":"","zhaiyao":"问热温热是否是飞"
                                // ,"content":"问热温热是否是飞问热温热是否是飞问热温热是否是飞问热温热是否是飞问热温热是否是
                                // 飞问热温热是否是飞问热温热是否是飞问热温热是否是飞问热温热是否是飞问热温热是否是飞问热温热是否是飞问热温热是否是飞",
                                // "sortId":"99","addTime":"2017\/6\/8 9:48:04","addName":"dg"}}
                                // {"msgcode":"1","msg":"成功","data":[{"id":2,"sendUser":"","title":"济南道路停车全面进入电子收费时代！","content":" 记者今天上午从济南市停车办了解到，" +
                                //        "市民今后可通过下载“济南停车”手机app、关注“济南停车”微信公众号、支付宝支付或现场扫码等多种渠道完成停车费支付操作。"
                                // ,"sendTime":"06\/13\/2017 00:00:00"}]}
                                if (TextUtils.equals("1", code)) {
                                    if (tag != 5) {
                                        title = obj.getJSONObject("data").getString("title");
                                        content = obj.getJSONObject("data").getString("content");
                                        date = obj.getJSONObject("data").getString("addTime");
                                        link = obj.getJSONObject("data").getString("linkUrl");
                                        showData();
                                    } else {
                                        JSONArray jsonArray = obj.getJSONArray("data");
                                        for (int i = 0; i < jsonArray.length(); i++) {
                                            JSONObject jsonObject = jsonArray.getJSONObject(i);
                                            title = jsonObject.getString("title");
                                            content = jsonObject.getString("content");
                                            date = jsonObject.getString("SendTime");
                                        }
                                       /* title=obj.getJSONObject("data").getString("title");
                                        content=obj.getJSONObject("data").getString("content");
                                        date=obj.getJSONObject("data").getString("sendTime");*/
                                        showData();
                                    }


                                } else if ("0".equals(code)) {
                                    try {
                                        CommonUtil.showToask(baseContext, obj.getString("msg"));
                                    } catch (Exception e) {
                                        ToastUtils.showShort("请求出错");
                                    }

                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    }, true);

        } catch (Exception e) {

        }


    }

    private void showData() {
        String str_canshu = "";
        switch (tag) {
            case 1:
            case 2:
            case 3:
            case 4:
            case 6:
                web.loadDataWithBaseURL(Urls.IP_IMAGE, content, "text/html",
                        "utf-8", null);
                break;
            case 7:
            case 8:
                web.loadUrl(link);
                break;
            case 5:
                String str_tz = "<!doctype html><html>\n<meta charset=\"utf-8\"><style type=\"text/css\">body{padding:0; margin:0;}\n." +
                        "view_h1{ width:90%%;display:block; "
                        + "overflow:hidden; margin:0 auto; font-size:1.2em; color:#333; padding-top:0.75em;padding-left:0.75em;padding-right:0,75em;"
                        + " line-height:1.2em; text-align:left;}\n.view_time{ width:90%; display:block; "
                        + "text-align:left;overflow:hidden; margin:0 auto; font-size:0.75em; color:#999;padding-top:0.75em;padding-bottom:0.75em;}\n.con{width:90%; "
                        + "margin:0 auto; color:#fff; color:#333;overflow:hidden; display:block; font-size:0.92em;"
                        + " line-height:1.8em;}\n.con h1,h2,h3,h4,h5,h6{ font-size:1em;}\n .con img{width: auto; max-width: 100%;"
                        + "height: auto;margin:0 auto;}\n</style>\n<body style=\"padding:0; margin:0; \">"
                        + "<div class=\"view_h1\">"
                        + title
                        + "</div><div class=\"view_time\">"
                        + "发布时间：" + date
                        + "</div><div class=\"con\">"
                        + content
                        + "</div></body><ml>";
                View mView = LayoutInflater.from(baseContext).inflate(R.layout.divide, null);
                web.addView(mView, 0, 60);
                web.loadDataWithBaseURL(Urls.IP, str_tz, "text/html",
                        "utf-8", null);
                break;
            default:
                break;
        }


    }

    WebChromeClient myChromeClient = new WebChromeClient() {
        private View myView = null;
        private CustomViewCallback myCallback = null;

        @Override
        public void onReceivedIcon(WebView view, Bitmap icon) {
            super.onReceivedIcon(view, icon);
        }

        @Override
        public void onGeolocationPermissionsShowPrompt(String origin, GeolocationPermissions.Callback callback) {
            super.onGeolocationPermissionsShowPrompt(origin, callback);
            callback.invoke(origin, true, true);
        }

        // 全屏播放调用
        @Override
        public void onShowCustomView(View view, CustomViewCallback callback) {
            super.onShowCustomView(view, callback);
            if (myCallback != null) {
                myCallback.onCustomViewHidden();
                myCallback = null;
                return;
            }
            // long id=Thread.currentThread().getId();

            ViewGroup parent = (ViewGroup) web.getParent();
            String s = parent.getClass().getName();
            parent.removeView(web);
            parent.addView(view);
            myView = view;
            myCallback = callback;

            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
        }

        // 非全屏播放时调用
        @Override
        public void onHideCustomView() {
            super.onHideCustomView();
            if (myView != null) {
                if (myCallback != null) {
                    myCallback.onCustomViewHidden();
                    myCallback = null;
                }

                ViewGroup parent = (ViewGroup) myView.getParent();
                parent.removeView(myView);
                parent.addView(web);
                myView = null;

                setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
            }
        }

    };

    @Override
    protected void onDestroy() {
        if (web != null) {
            ViewGroup viewGroup = (ViewGroup) web.getParent();
            if (viewGroup != null) {
                viewGroup.removeView(web);
            }
            web.destroyDrawingCache();
            web.destroy();
        }
        super.onDestroy();
        /*if (web != null) {

            web.destroy();
        }*/
    }
}
